package redisutil

import (
	"fmt"
	"path/filepath"

	"net/url"
	"strconv"
	"strings"

	"gitee.com/liuyl162/utils/maputil"
	"github.com/go-redis/redis"
)

//uri格式 redis://[:password@]localhost:6379/dbn
//返回 host:port, dbn, pass,error
func ParseRedisUri(redis_uri string) (string, int, string, error) {
	host, port, dbn, pass := "localhost", 6379, 0, ""
	if u, e := url.Parse(redis_uri); e != nil {
		return "", 0, "", fmt.Errorf("无效URI: %s %s", redis_uri, e.Error())
	} else {
		if h := u.Host; h != "" {
			host = strings.Split(h, ":")[0]
		}
		if p, e := strconv.Atoi(u.Port()); e == nil {
			port = p
		}
		if p, e := strconv.Atoi(filepath.Base(u.Path)); e == nil {
			dbn = p
		}
		u.User.Username()
		if p, has := u.User.Password(); has {
			pass = p
		} else if n := u.User.Username(); n != "" {
			pass = n
		}
	}
	return fmt.Sprintf("%s:%d", host, port), dbn, pass, nil
}

// uri格式 redis://[auth@]localhost:6379/dbn
//uri中的auth部分不可以包含:
//passwd优先级高于uri中的auth部分
func Connect(uri, passwd string) (*redis.Client, error) {
	addr, db, auth, err := ParseRedisUri(uri)
	if passwd != "" {
		auth = passwd
	}
	fmt.Println(addr, db, auth)
	if err != nil {
		return nil, err
	}
	opt := &redis.Options{
		Addr:     addr,
		Password: auth,
		DB:       db,
	}
	rds := redis.NewClient(opt)
	return rds, nil
}

//key为redis中的hash的键，subkeys为空格分隔的子key列表
func HMget(cli *redis.Client, key, subkeys string) (map[string]interface{}, error) {
	keys := strings.Split(subkeys, " ")
	vals, err := cli.HMGet(key, keys...).Result()
	if err != nil {
		return nil, fmt.Errorf("redis.hmget err:%s", err.Error())
	}

	return maputil.JoinToMap(keys, vals), nil
}

func Mget(cli *redis.Client, keys_space string) (map[string]interface{}, error) {
	keys := strings.Split(keys_space, " ")
	vals, err := cli.MGet(keys...).Result()
	if err != nil {
		return nil, fmt.Errorf("redis.mget err:%s", err.Error())
	}

	return maputil.JoinToMap(keys, vals), nil
}
